package service

import (
	"github.com/fsnotify/fsnotify"
	"github.com/wonderivan/logger"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

func (s *service) Connector() (connector *Connector, err error) {
	var ok bool
	if connector, ok = s.rummyNodeList.Next().(*Connector); !ok {
		logger.Warn("Connector_Fetch_Fail | err: %s", err.Error())
		return
	}
	return
}

func (s *service) ConnectorWatcher() (err error) {
	var (
		watcher *fsnotify.Watcher
	)
	err = s.reloadRummyNode(s.conf.RummyNode)
	if err != nil {
		return
	}
	go func() {
		watcher, err = fsnotify.NewWatcher()
		if err != nil {
			logger.Fatal("watch rummy node list fail, %s", err.Error())
			return
		}
		watcher.Add(s.conf.RummyNode)
		for {
			select {
			case evt := <-watcher.Events:
				{
					logger.Info("rummy node modified, evt %s", evt.String())
					switch evt.Op {
					case fsnotify.Write, fsnotify.Create:
						s.reloadRummyNode(s.conf.RummyNode)
					case fsnotify.Remove, fsnotify.Rename:
						logger.Error("rummy node list file can't load")
					}
				}
			}
		}
	}()
	return
}

func (s *service) reloadRummyNode(nodeConf string) (err error) {
	var (
		bs            []byte
		rummyNodeList map[string][]*Connector
	)
	defer func() {
		if r := recover(); r != nil {
			logger.Error("recovered, %+v", r)
		}
	}()

	rummyNodeList = map[string][]*Connector{}
	bs, err = ioutil.ReadFile(nodeConf)
	if err != nil {
		logger.Error("config file load fail: %s", err.Error())
		return
	}
	err = yaml.Unmarshal(bs, rummyNodeList)
	if err != nil {
		logger.Error("unmarshal rummy node fail, %s", err.Error())
		return
	}
	s.rummyNodeList.RemoveAll()
	for _, node := range rummyNodeList["node"] {
		s.rummyNodeList.Add(node, node.Weight)
	}
	logger.Info("rummy node reloaded | total: %d", len(rummyNodeList["node"]))
	return
}
